package cn.cachalot.oj.interceptor;

import cn.cachalot.oj.util.BaseContext;
import cn.cachalot.oj.util.R;
import cn.cachalot.oj.util.TokenUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("ASDASDASD");
        log.info(request.getRequestURI());
        String token = request.getHeader("token");
        if (token != null) {
            if (TokenUtil.checkToken(token)) {
                Long userId = Long.valueOf(Objects.requireNonNull(TokenUtil.getUserIdFromToken(token)));
                Integer level = TokenUtil.getUserLevelFromToken(token);
                BaseContext.setId(userId);
                BaseContext.setLevel(level);
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(JSON.toJSONString(R.error("token验证失败!").code(401)));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
